﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace TotalFreedomKO
{
    public static class KoHelper
    {
        public static string KoModelAndProperty<TModel, TProperty>(Expression<Func<TModel, TProperty>> expression)
        {
            string result = "";

            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, null);
            if (metadata != null)
                result = metadata.DataTypeName + "()" + metadata.PropertyName + "()";

            return result;
        }

        public static string GetRootContext()
        {
            return "ko.contextFor(this).$root";
        }

        public static string GetDataContext()
        {
            return "ko.contextFor(this).$data";
        }

        public static string GetParentContext()
        {
            return "ko.contextFor(this).$parent";
        }

        public static string ComputedJavaScript<TModel>(Expression<Func<TModel, object>> expression)
        {
            string result = "";

            PropertyData data = KoHelperExtensions.GetPropertyData(expression, propertyNamePrefix: "self.");
            if (data != null)
                result = "return " +  data.Expression + ";";

            return result;
        }        

        public static string ComputedFromFile(string fileName)
        {
            string result = System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath(fileName));

            return result;
        }
    }
}
